﻿using Sidvall.Collections;
using Sidvall.Serialization;

namespace Sidvall.WorkItemManager.Workflow
{
	public class WorkItemContext
	{
		[System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Performance", "CA1819:PropertiesShouldNotReturnArrays")]
		public long[] WorkerIds { get; set; }
		public string PluginPath { get; set; }
		public bool IsTestRun { get; set; }
		public bool CleanLog { get; set; }

		#region GetWorkItemContext

		public static WorkItemContext GetWorkItemContext(string configArgs, string[] args, WorkItemExecutionContext executionContext)
		{
			WorkItemContext item;

			item = new WorkItemContext()
			{
				IsTestRun = false,
				WorkerIds = null,
			};
			if ((args == null) || (args.Length < 2))
				args = configArgs.Split(" ", System.StringSplitOptions.RemoveEmptyEntries);
			if ((args != null) && (args.Length >= 2))
			{
				switch (args[0].ToUpperInvariant())
				{
					case "TEST":
						item.IsTestRun = true;
						break;
					case "RUN":
						item.IsTestRun = false;
						break;
					default:
						throw new System.ArgumentException("use the syntax: Sidvall.WorkItemManager.Worker <test/run> <worker ids> [plugin path] <CleanLog 1/0>");
				}
				item.WorkerIds = args[1].Split(",", System.StringSplitOptions.RemoveEmptyEntries).ToInt64Array();
				if (args.Length >= 3)
					item.PluginPath = args[2];
				if (args.Length >= 4)
					item.CleanLog = args[3].ToBoolean(false);
			}
			if (executionContext != null)
			{
				if (item.CleanLog)
				{
					if ((executionContext.LastCleanLogTime == null) || (executionContext.LastCleanLogTime.Value.Date != System.DateTime.Today))
						executionContext.LastCleanLogTime = System.DateTime.Today;
					else
						item.CleanLog = false;
				}
			}
			return item;
		}

		#endregion
	}
}
